package com.peternguyen.totolistpro;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.peternguyen.totolistpro.dao.AccountDAO;
import com.peternguyen.totolistpro.dao.TodoDAO;
import com.peternguyen.totolistpro.data.Account;
import com.peternguyen.totolistpro.data.Category;
import com.peternguyen.totolistpro.data.ToDo;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity implements OnClickListener {

	// action id
	private static final int ID_ADD_WORK = 1;
	private static final int ID_TODAY = 2;
	private static final int ID_ALL = 3;	
	private static final int ID_TOMORROW = 4;
	private static final int ID_IMPORT = 5;
	private static final int ID_MANAGER_GROUP = 6;
	private static final int ID_CHGPWD = 7;
	private static final int ID_SETTING = 8; // vIEC CO QUAN
	private static final int ID_EXIT = 9;
	private static final int ID_NEARDUEDATE = 10;
	private static final int ID_NEARDATE = 11;
	private static final int VIEW_TD_ALL = 12;
	private static final int VIEW_TD_TODAY = 13;
	private static final int VIEW_TD_TOMORROW = 14;
	private static final int VIEW_TD_IMPORT = 15;
	private static final int VIEW_TD_DUEDATE = 16;
	private static final int VIEW_TD_NEWTODAY = 17;	

	private static final String CATEGORY_NAME = "";

	private int viewType = 0;

	private ImageButton btn_menu;
	private EditText txtContent;
	TodoDAO tdDao;
	private ImageButton btnAddTask;
	ListView list;

	ToDoAdapter adapter;
	ArrayList<ToDo> lstTodo;
	private ArrayList<ToDo> lv_arr;
	EditText txtSearch;

	private Account acc;
	private AccountDAO accDao;
	Category cat;

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		LoadListView();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		tdDao = new TodoDAO(this);
		accDao = new AccountDAO(this);
		acc = accDao.getAccount();
		btnAddTask = (ImageButton) findViewById(R.id.btnAddTask);
		txtContent = (EditText) findViewById(R.id.quickAddText);
		btnAddTask.setOnClickListener(this);
		setTitle(R.string.title_today);
		// Kiem tra truong hop todo tu cho khac goi
		// Lay thong tin
		
		cat = (Category) getIntent().getSerializableExtra(
				CategoryActivity.CATEGORY);
		if (cat != null) {
			// setTitle("Thuy vy");
			Log.i("ID", String.valueOf(cat.get_name()));
			setTitle(getString(R.string.title_g) + " " + cat.get_name());
			LoadListView();
		}

		ActionItem mnu_add = new ActionItem(ID_ADD_WORK,
				getString(R.string.mnu_add), getResources().getDrawable(
						R.drawable.tango_add));

		ActionItem mnu_all = new ActionItem(ID_ALL,
				getString(R.string.mnu_all), getResources().getDrawable(
						R.drawable.today));
		
		ActionItem mnu_today = new ActionItem(ID_TODAY,
				getString(R.string.mnu_today), getResources().getDrawable(
						R.drawable.today));

		ActionItem mnu_tomorrow = new ActionItem(ID_TOMORROW,
				getString(R.string.mnu_tomorrow), getResources().getDrawable(
						R.drawable.tomorrow));

		ActionItem mnu_import = new ActionItem(ID_IMPORT,
				getString(R.string.mnu_import), getResources().getDrawable(
						R.drawable.todo_import22));

		ActionItem mnu_neardueday = new ActionItem(ID_NEARDUEDATE,
				getString(R.string.mnu_duedate), getResources().getDrawable(
						R.drawable.nearduedate22));

		ActionItem mnu_nearday = new ActionItem(ID_NEARDATE,
				getString(R.string.mnu_neardate), getResources().getDrawable(
						R.drawable.neartodo));

		ActionItem mnu_groupwork = new ActionItem(ID_MANAGER_GROUP,
				getString(R.string.mnu_category), getResources().getDrawable(
						R.drawable.default_list_1));

		ActionItem mnu_chwgpwd = new ActionItem(ID_CHGPWD,
				getString(R.string.chg_pwd), getResources().getDrawable(
						R.drawable.key));

		ActionItem mnu_setting = new ActionItem(ID_SETTING,
				getString(R.string.mnu_setting), getResources().getDrawable(
						R.drawable.settings22));

		ActionItem mnu_exit = new ActionItem(ID_EXIT, getString(R.string.exit),
				getResources().getDrawable(R.drawable.exit));

		// use setSticky(true) to disable QuickAction dialog being dismissed
		// after an item is clicked
		// prevItem.setSticky(true);
		mnu_add.setSticky(true);

		// create QuickAction. Use QuickAction.VERTICAL or
		// QuickAction.HORIZONTAL param to define layout
		// orientation
		final QuickAction quickAction = new QuickAction(this,
				QuickAction.VERTICAL);

		// add action items into QuickAction
		quickAction.addActionItem(mnu_add);
		quickAction.addActionItem(mnu_all);
		quickAction.addActionItem(mnu_today);		
		quickAction.addActionItem(mnu_tomorrow);
		quickAction.addActionItem(mnu_import);
		quickAction.addActionItem(mnu_nearday);
		quickAction.addActionItem(mnu_neardueday);
		quickAction.addActionItem(mnu_groupwork);
		quickAction.addActionItem(mnu_chwgpwd);
		quickAction.addActionItem(mnu_setting);

		quickAction.addActionItem(mnu_exit);

		// Set listener for action item clicked
		quickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction source, int pos,
							int actionId) {
						// here we can filter which action item was clicked with
						// pos or actionId parameter
						if (actionId == ID_ADD_WORK) {
							Intent i = new Intent(MainActivity.this,
									EditTodo.class);
							startActivity(i);
							quickAction.dismiss();
						} else if (actionId == ID_ALL) {
							viewType = VIEW_TD_ALL;
							LoadListView();
							setTitle(R.string.title_all);
						} 
						else if (actionId == ID_TODAY) {
							viewType = VIEW_TD_TODAY;
							LoadListView();
							setTitle(R.string.title_today);

						} else if (actionId == ID_TOMORROW) {
							viewType = VIEW_TD_TOMORROW;
							LoadListView();
							setTitle(R.string.title_tomorrow);

						} else if (actionId == ID_NEARDUEDATE) {
							viewType = VIEW_TD_DUEDATE;
							LoadListView();
							setTitle(R.string.title_duedate);

						} else if (actionId == ID_IMPORT) {
							viewType = VIEW_TD_IMPORT;
							LoadListView();
							setTitle(R.string.title_import);

						} else if (actionId == ID_NEARDATE) {
							viewType = VIEW_TD_NEWTODAY;
							LoadListView();
							setTitle(R.string.title_recent);

						} else if (actionId == ID_SETTING) {
							Intent ic = new Intent(MainActivity.this,
									ActivityConfig.class);
							startActivity(ic);
							setTitle(R.string.app_name);

						} else if (actionId == ID_CHGPWD) {
							final AlertDialog.Builder alert = new AlertDialog.Builder(
									MainActivity.this);

							LinearLayout lila1 = new LinearLayout(
									MainActivity.this);
							lila1.setOrientation(1); // 1 is for vertical
														// orientation
							final EditText pwdold = new EditText(
									MainActivity.this);
							pwdold.setHint(R.string.pwd_old);
							pwdold.setInputType(InputType.TYPE_CLASS_TEXT
									| InputType.TYPE_TEXT_VARIATION_PASSWORD);

							final EditText pwdnew = new EditText(
									MainActivity.this);
							pwdnew.setHint(R.string.pwd_new);
							pwdnew.setInputType(InputType.TYPE_CLASS_TEXT
									| InputType.TYPE_TEXT_VARIATION_PASSWORD);

							lila1.addView(pwdold);
							lila1.addView(pwdnew);
							alert.setView(lila1);

							alert.setIcon(R.drawable.icon);
							alert.setTitle(getString(R.string.chg_pwd));

							alert.setPositiveButton(R.string.login_ok,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											String old = accDao.getAccount()
													.get_pwd();
											if (old.equals(pwdold.getText()
													.toString())) {
												// Cap nhat
												accDao.UpdatePWD(acc.get_id(),
														pwdnew.getText()
																.toString()
																.trim(),
														"itnguyennam@gmail.com");
												Toast.makeText(
														getApplicationContext(),
														getString(R.string.update_sec),
														Toast.LENGTH_SHORT)
														.show();
											} else {
												Toast.makeText(
														getApplicationContext(),
														getString(R.string.pw_valid),
														Toast.LENGTH_SHORT)
														.show();
											}
										}
									});
							alert.setNegativeButton(R.string.login_cancel,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											dialog.cancel();
										}
									});
							alert.show();
						} else if (actionId == ID_MANAGER_GROUP) {
							setTitle(R.string.mnu_category);
							Intent i = new Intent(MainActivity.this,
									CategoryActivity.class);
							startActivity(i);
							// MainActivity.this.finish();
						} else {
							// Neu la IDEXIT thif laf thoat
							MainActivity.this.finish();
						}
					}
				});

//		quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
//			@Override
//			public void onDismiss() {
//				Toast.makeText(getApplicationContext(), "Dismissed",
//						Toast.LENGTH_SHORT).show();
//			}
//		});
		// Clic menu
		ImageButton btnMenu = (ImageButton) this.findViewById(R.id.btn_menu);
		btnMenu.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				quickAction.show(v);
			}
		});
		list = (ListView) findViewById(R.id.listtodo);
		viewType = VIEW_TD_ALL;
		LoadListView();
		// lstTodo = new ArrayList<ToDo>();
		// lv_arr = PrepareList();
		//
		// for (ToDo item : lv_arr) {
		// // creating new HashMap
		// ToDo map = new ToDo();
		// // Element e = (Element) nl.item(i);
		// // adding each child node to HashMap key => value
		// map.set_id(Integer.valueOf(item.get_id()));
		// map.set_name(String.valueOf(item.get_name()));
		// map.set_catid(item.get_catid());
		// map.set_priority(item.get_priority());
		// map.set_deadline_date(item.get_deadline_date());
		// // map.set_img(item.get_img());
		// Log.i("ThuyVy", String.valueOf(item.get_deadline_date()));
		// Log.i("Name", String.valueOf(item.get_name()));
		// // Log.i("Link", String.valueOf(item.get_link()));
		//
		// // adding HashList to ArrayList
		// lstTodo.add(map);
		// }
		// adapter = new ToDoAdapter(this, lstTodo);
		// list.setAdapter(adapter);
		/*
		 * btn_menu = (Button) findViewById(R.id.btn_menu);
		 * btn_menu.setOnClickListener(this);
		 */

		// Search
		txtSearch = (EditText) findViewById(R.id.txtSeachTodo);
		list.setTextFilterEnabled(true);
		txtSearch.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// // TODO Auto-generated method stub
				// btnSearchView
				Log.i("Search", String.valueOf(arg0));

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				lstTodo = new ArrayList<ToDo>();
				for (ToDo td : lv_arr) {
					if (td.get_name().toString()
							.contains(txtSearch.getText().toString())) {
						lstTodo.add(td);
					}
				}
				// LoadListView();
				// lv_arr =(ArrayList<ToDo>) lstTodo;
				adapter = new ToDoAdapter(MainActivity.this, lstTodo);
				list.setAdapter(adapter);
			}
		});

		// Click event for single list row
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				// list.getAdapter().getItem(arg0)
				ToDo td = lv_arr.get(position);

				Log.i("ID", String.valueOf(td.get_name()));
				Log.i("position", String.valueOf(position));

				Intent edit = new Intent(MainActivity.this, EditTodo.class);
				Bundle myBundle = new Bundle();
				myBundle.putSerializable("ToDo", td);
				edit.putExtra("Data", myBundle);
				startActivity(edit);
				// Object o = list.getItemAtPosition(position);
				// ToDo obj_itemDetails = (ToDo)o;
				// Toast.makeText(v.getContext(),
				// "You have chosen : " + " "
				// + obj_itemDetails.get_name(), Toast.LENGTH_LONG).show();

			}
		});

	}

	// private ArrayList<ToDo> PrepareList() {
	// tdDao = new TodoDAO(MainActivity.this);
	// List<ToDo> lst = new ArrayList<ToDo>();
	// if (today) {
	// lst = tdDao.getTodoToday();
	// today = false;
	//
	// } else if (tomorrow) {
	// lst = tdDao.getTodoTomorrow();
	//
	// } else if (td_import) {
	// lst = tdDao.getTodoImport();
	//
	// } else if (td_duedate) {
	// lst = tdDao.getTodoDuedate("numday_duedate", "+");
	//
	// } else if (td_newtoday) {
	// lst = tdDao.getTodoDuedate("newtoday", "-");
	//
	// } else if (cat != null) {
	//
	// lst = tdDao.getList(cat.get_id());
	//
	// } else {
	// lst = tdDao.getList();
	// }
	//
	// List<ToDo> temp = new ArrayList<ToDo>();
	// for (ToDo item : lst) {
	// temp.add(item);
	// }
	// return (ArrayList<ToDo>) temp;
	// }

	public void LoadListView() {

		tdDao = new TodoDAO(MainActivity.this);
		List<ToDo> lst = new ArrayList<ToDo>();
		if (cat != null) {
			lst = tdDao.getList(cat.get_id());

		} 
		else {
			switch (viewType) {
			case VIEW_TD_TODAY:
				lst = tdDao.getTodoToday();
				break;
			case VIEW_TD_TOMORROW:
				lst = tdDao.getTodoTomorrow();
				break;
			case VIEW_TD_IMPORT:
				lst = tdDao.getTodoImport();
				break;
			case VIEW_TD_DUEDATE:
				lst = tdDao.getTodoDuedate("numday_duedate", "+");
				break;
			case VIEW_TD_NEWTODAY:
				lst = tdDao.getTodoDuedate("newtoday", "-");
				break;
			default:
				lst = tdDao.getList();
				break;
			}
		}
		
		lv_arr = (ArrayList<ToDo>) lst;
		adapter = new ToDoAdapter(this, lv_arr);
		list.setAdapter(adapter);

		// lv_arr = PrepareList();
		// lstTodo = new ArrayList<ToDo>();
		//
		// for (ToDo item : lv_arr) {
		// // creating new HashMap
		// ToDo map = new ToDo();
		// // Element e = (Element) nl.item(i);
		// // adding each child node to HashMap key => value
		// map.set_id(Integer.valueOf(item.get_id()));
		// map.set_name(String.valueOf(item.get_name()));
		// map.set_catid(item.get_catid());
		// map.set_priority(item.get_priority());
		// map.set_deadline_date(item.get_deadline_date());
		// /*
		// * byte[] outImage = item.get_img(); ByteArrayInputStream
		// * imageStream = new ByteArrayInputStream(outImage); Bitmap theImage
		// * = BitmapFactory.decodeStream(imageStream);
		// * holder.imgIcon.setImageBitmap(theImage); map.put(KEY_ARTIST,
		// * String.valueOf(item.get_img()));
		// */
		// // map.put(KEY_ARTIST, String.valueOf(item.get_link()));
		// //
		// Log.i("get_deadline_date", String.valueOf(item.get_deadline_date()));
		// // Log.i("Link", String.valueOf(item.get_link()));
		//
		// // adding HashList to ArrayList
		// lstTodo.add(map);
		// }
		// adapter = new ToDoAdapter(this, lstTodo);
		// list.setAdapter(adapter);

	}

	@Override
	public void onClick(View v) {
		int key = v.getId();
		switch (key) {
		case R.id.btn_menu:
			break;

		case R.id.btnAddTask:
			tdDao = new TodoDAO(this);
			ToDo td = new ToDo();
			td.set_name(txtContent.getText().toString());
			td.set_deadline_date(new Date());
			if (cat != null) {
				td.set_catid(cat.get_id());
			} else {
				td.set_catid(1);
			}
			tdDao.Add(td);
			LoadListView();
			Toast.makeText(getApplicationContext(),
					getString(R.string.save_success), Toast.LENGTH_SHORT)
					.show();
			break;

		default:
			break;
		}

	}

}
